package com.siwei.eqi.util;



import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    // OkHttp 客户端实例（单例模式）
    private static final OkHttpClient HTTP_CLIENT;

    static {
        // 配置超时时间
        HTTP_CLIENT = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)   // 连接超时
                .readTimeout(30, TimeUnit.SECONDS)      // 读取超时
                .writeTimeout(30, TimeUnit.SECONDS)     // 写入超时
                .build();
    }

    /**
     * GET 请求
     * @param url     请求地址
     * @param params  URL参数（可空）
     * @param headers 请求头（可空）
     * @return 响应内容字符串
     */
    public static String get(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            params.forEach(urlBuilder::addQueryParameter);
        }
        Request.Builder requestBuilder = new Request.Builder().url(urlBuilder.build());
        addHeaders(requestBuilder, headers);
        return executeRequest(requestBuilder.build());
    }

    /**
     * POST 表单请求
     * @param url    请求地址
     * @param form   表单参数（可空）
     * @param headers 请求头（可空）
     */
    public static String postForm(String url, Map<String, String> form, Map<String, String> headers) throws IOException {
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (form != null) {
            form.forEach(formBuilder::add);
        }
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(formBuilder.build());
        addHeaders(requestBuilder, headers);
        return executeRequest(requestBuilder.build());
    }

    /**
     * POST JSON 请求
     * @param url    请求地址
     * @param json   JSON字符串
     * @param headers 请求头（可空）
     */
    public static String postJson(String url, String json, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        addHeaders(requestBuilder, headers);
        return executeRequest(requestBuilder.build());
    }

    /**
     * 通用请求执行方法
     */
    private static String executeRequest(Request request) throws IOException {
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败，状态码: " + response.code());
            }
            return response.body() != null ? response.body().string() : null;
        }
    }

    /**
     * 添加请求头
     */
    private static void addHeaders(Request.Builder builder, Map<String, String> headers) {
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
    }

}
